package demo4.mapper;

import demo4.pojo.User;
import demo4.util.IDBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 李明洋
 * @date 2025/3/28 16:57
 * @version: 1.0
 */
@Component
public class UserMapper implements IUserMapper{
    @Autowired
    private IDBUtil idbUtil;
    public int insert(User user){
        System.out.println("UserMapper:插入数据");
        try (Connection connection = idbUtil.getConnection();){
            String sql = "INSERT INTO user(username,password,nickname,age) VALUES(?,?,?,?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getNickname());
            ps.setInt(4,user.getAge());
            return ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    @Override
    public User selectByUsername(String username){
        try (Connection connection = idbUtil.getConnection();){
            String sql = "SELECT id,username,password,nickname,age from user where username=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getNString("username"));
                user.setPassword(rs.getNString("password"));
                user.setNickname(rs.getNString("nickname"));
                user.setAge(rs.getInt("age"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
